package com.ningjingjing.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ningjingjing.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 1.判断用户是否登录
 * 2.根据API规定结果格式，构造相应的对象
 * 3.把用户对象序列化成JSON字符串
 * 4.将结果写入resp中
 */


@WebServlet("/api/current-user.json")
public class CurrentUserApi extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 这里的代码用于临时测试，测试有登录信息的具体表现
//        {
//            User user = new User();
//            user.uid = 001;
//            user.nickname = "宁静静";
//            user.username = "ningjingjing";
//            HttpSession session = req.getSession();
//            session.setAttribute("currentUser", user);
//        }

        // 判定目前是否有用户处于登录状态
        HttpSession session = req.getSession();
        User currentUser = (User)session.getAttribute("currentUser");
        Object result;
        if (currentUser == null) {
            // 用户未登录

            // 使用匿名类，可以不用专门去定义一个结果对象
            result = new Object() {
                public boolean logged = false;
            };
        } else {
            // 用户已登录
            result = new Object() {
                public boolean logged = true;
                public User user = currentUser;
            };
        }

        // 将对象序列化成 JSON 字符串
        String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);

        // 将 JSON 字符串放入 resp 对象中
        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().println(json);
    }
}